/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.cells.opreate;

import cn.ac.nercis.pes.community.utils.IconUtils;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;

import java.util.Objects;

/**
 * 单一操作按钮操作列
 * @param <T>
 * @author zpy
 * @version 1.0.0
 */
public class SingleOperateTableCell<T>  extends TableCell<T,String> {
    private final Button optButton = new Button();
    private final EventHandler<? super MouseEvent> optClickEvent;
    private final TableView<T> tableView;
    private final String optTooltip;
    private final String optIcon;

    public SingleOperateTableCell(TableView<T> tableView,String tooltip,String optIcon,
                                  EventHandler<? super MouseEvent> optClickEvent) {
        this.optIcon = optIcon;
        this.optTooltip=tooltip;
        this.tableView = tableView;
        this.optClickEvent = optClickEvent;
        this.init();
    }

    private void init(){
        optButton.getStyleClass().add("tab-option-btn");
        optButton.setGraphic(IconUtils.getGlyph(optIcon,"sys-eval-button-icon"));
        optButton.setTooltip(new Tooltip(optTooltip));
        optButton.setOnMouseClicked(event -> {
            tableView.getSelectionModel().select(getIndex());
            if(Objects.nonNull(optClickEvent)){
                optClickEvent.handle(event);
            }
        });
    }

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setGraphic(null);
        } else {
            HBox hBox = new HBox(optButton);
            hBox.setSpacing(0);
            hBox.setAlignment(Pos.CENTER);
            setGraphic(hBox);
        }
    }
}